#include "gameboard.h"

#include <QDebug>
#include <QString>

#include "peg.h"
#include "hole.h"

GameBoard::GameBoard(QObject *parent) :
    QGraphicsScene(parent)
{
    const GameBoardConfiguration m_board_configuration[m_height][m_width] = {
        {_, _, X, X, X, _, _},
        {_, _, X, X, X, _, _},
        {X, X, X, X, X, X, X},
        {X, X, X, O, X, X, X},
        {X, X, X, X, X, X, X},
        {_, _, X, X, X, _, _},
        {_, _, X, X, X, _, _},
    };

    for (size_t i = 0; i < m_height; ++i) {
        for (size_t j = 0; j < m_width; ++j) {
            switch (m_board_configuration[i][j]) {
                case O: {
                        Hole *hole = new Hole(i, j, 20);
                        addItem(hole);
                        m_board[i][j] = hole;
                    }
                    break;
                case X: {
                        Hole *hole = new Hole(i, j, 20);
                        addItem(hole);
                        addItem(new Peg(hole));
                        m_board[i][j] = hole;
                    }
                    break;
                default:
                    m_board[i][j] = NULL;
                    break;
            }
        }
    }
}

bool GameBoard::putPeg(const QPoint &target, Peg *peg)
{
    Hole *hole = this->hole(target);
    if (!hole->havePeg()) {
        hole->setPeg(peg);
        peg->setHole(hole);
        peg->setPos(hole->pos());
        return true;
    }
    return false;
}

bool GameBoard::movePeg(const QPoint &source, const QPoint &target)
{
    Peg *peg = removePeg(source);
    if (!peg) {
        return false;
    }
    return putPeg(target, peg);
}

Peg *GameBoard::removePeg(const QPoint &pos)
{
    Hole *hole = this->hole(pos);
    Peg *removed_peg = NULL;
    if (hole) {
        removed_peg = hole->setPeg(NULL);
        if (removed_peg) {
            removed_peg->setHole(NULL);
//            removed_peg->setPos(0, 0);
        }
    }
    return removed_peg;
}

bool GameBoard::removePegFromTheBoard(const QPoint &pos)
{
    Peg *removed_peg = removePeg(pos);
    if (removed_peg) {
        delete removed_peg;
        return true;
    }
    return false;
}

Hole *GameBoard::hole(const QPoint &pos) const
{
    return m_board[pos.x()][pos.y()];
}

void GameBoard::printBoard()
{
    for (size_t i = 0; i < m_height; ++i) {
        QString line;
        for (size_t j = 0; j < m_width; ++j) {
            Hole *hole = m_board[j][i];
            if (hole) {
                if (hole->havePeg()) {
                    line += "X";
                } else {
                    line += "O";
                }
            } else {
                line += "_";
            }
        }
        qDebug() << line;
    }
    qDebug() << "";
}
